package com.itheima.health.service.impl;

import com.alibaba.druid.util.StringUtils;
import com.itheima.health.common.MessageConst;
import com.itheima.health.dao.MemberDao;
import com.itheima.health.dao.OrderDao;
import com.itheima.health.dao.OrderSettingDao;
import com.itheima.health.dao.SetMealDao;
import com.itheima.health.exception.BusinessRuntimeException;
import com.itheima.health.pojo.Member;
import com.itheima.health.pojo.Order;
import com.itheima.health.pojo.OrderSetting;
import com.itheima.health.pojo.Setmeal;
import com.itheima.health.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 预约ServiceImpl
 */
@Service
@Slf4j
public class OrderServiceImpl implements OrderService {
    @Autowired
    private OrderSettingDao orderSettingDao;
    @Autowired
    private OrderDao orderDao;
    @Autowired
    private MemberDao memberDao;
    @Autowired
    private SetMealDao setMealDao;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 提交预约信息
     *
     * @param map
     */
    @Override
    @Transactional
    public Order addOrder(Map map) {

        //第一步:先判断用户的验证码是否正确  验证码正确的话redis中验证码进行删除
        String validateCode = (String) redisTemplate.opsForValue().get("ORDER" + "_" + map.get("telephone"));
        String userValidateCode = (String) map.get("validateCode");
        String telephone = map.get("telephone").toString();

        //验证验证码和手机号是否为空
        if (StringUtils.isEmpty(userValidateCode) && StringUtils.isEmpty(telephone)) {
            throw new BusinessRuntimeException(MessageConst.TELEPHONE_VALIDATECODE_NOTNULL);
        }
        //验证码是否正确
        if (!(validateCode.equals(userValidateCode))) {
            throw new BusinessRuntimeException(MessageConst.VALIDATECODE_ERROR);
        }


        //第二步判断用户输入的日期是否符合预约条件
        Object orderDate2 = map.get("orderDate");
        if (orderDate2 == null) {
            throw new BusinessRuntimeException(MessageConst.ORDER_DATE_NULL);
        } else {
            OrderSetting orderDate1 = orderSettingDao.getOrderSettingByOrderDate(orderDate2.toString());
            if (orderDate1 == null) {
                throw new BusinessRuntimeException(MessageConst.SELECTED_DATE_CANNOT_ORDER);
            }
        }


        //第三步:判断传过来的日期是否是当前日期以后的日期
        String orderDate = map.get("orderDate").toString();
        Date date = null;   //预约时间
        Date date2 = null;  //系统当前时间
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        try {
            date = sdf.parse(orderDate);
            String stringDate = sdf.format(new Date());
            date2 = sdf.parse(stringDate);
            //如果传过来的日期小于当前日期,则抛出异常
            if (date.before(date2)) {
                throw new BusinessRuntimeException(MessageConst.SELECTED_DATE_CANNOT_ORDER);
            }
        } catch (ParseException e) {
            throw new RuntimeException(e);
        }


        //第四步先判断该套餐还有没有预约名额 ,如果没有名额 进行响应
        OrderSetting orderSetting = orderSettingDao.getOrderSettingByOrderDate(orderDate);
        if (orderSetting.getNumber() <= orderSetting.getReservations()) {
            throw new BusinessRuntimeException(MessageConst.ORDER_FULL);
        }

        //第五步判断该用户时候为 会员如果是不是会员  要进行添加会员 是会员更新会员信息
        Member member = memberDao.getMember(telephone);

        if (member == null) {
            Member member1 = new Member();
            member1.setName(map.get("name").toString());
            member1.setSex(map.get("sex").toString());
            member1.setIdCard(map.get("idCard").toString());
            member1.setPhoneNumber(telephone);
            member1.setRegTime(date2);
            //添加到数据库
            memberDao.addMember(member1);
        }else {
            member.setIdCard(map.get("idCard").toString());
            memberDao.updateMember(member);
        }

        //第六步进行判断用户预约的日期中是否已经预约了过了()其他套餐  如果预约过提示预约过
        //通过用户的电话号和会员号判断该用户在改天是否已经预约过了
        Integer memberId = memberDao.getMemberIdByPhoneNumber(telephone);
        Order order = orderDao.getOrderByOrderDateAndMemberId(orderDate, memberId);
        if (order != null) {
            throw new BusinessRuntimeException(MessageConst.ORDER_SETTING_EXIST);
        }


        //第七步: 如果是会员 要进行保存到预约单中
        Order order1 = new Order();
        order1.setMemberId(memberId);
        order1.setOrderDate(date);
        order1.setOrderType("微信预约");
        order1.setOrderStatus("未到诊");
        order1.setSetmealId(Integer.parseInt(map.get("setmealId").toString()));
        orderDao.addOrder(order1);

        //第八步并且将t_ordertring)的已经预约数量加一
        orderSettingDao.updateOrderSettingByOrderDate(map.get("orderDate").toString());

        //第九步:删除redis中的验证码
        redisTemplate.delete("ORDER" + "_" + map.get("telephone"));

        return order1;
    }

    /**
     * 体检预约信息成功
     *
     * @param id
     * @return
     */
    @Override
    public Map<String, String> getOrderById(Integer id) {

        Map<String, String> map = new HashMap<>();
        Order order = orderDao.getOrderById(id);
        Member member = memberDao.getMemberById(order.getMemberId());
        Setmeal setmeal = setMealDao.getSetmealById(order.getSetmealId());

        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");

        map.put("member", member.getName());
        map.put("orderDate", sdf.format(order.getOrderDate()));
        map.put("orderType", order.getOrderType());
        map.put("setmeal", setmeal.getName());
        return map;
    }

}
